package com.netty.source;

import com.netty.hanler.ServerChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * 源码学习，服务端代码
 */
public class SourceStart {

    private ServerBootstrap bootstrap;
    private final NioEventLoopGroup eventLoop;
    private final EventLoopGroup work;
    private ChannelHandler[] handlers;

    public SourceStart() {
        eventLoop = new NioEventLoopGroup(1);
        work = new NioEventLoopGroup();
    }

    public SourceStart(ChannelHandler... handlers) {
        this();
        this.handlers = handlers;
    }

    public void start() throws InterruptedException {
        this.bootstrap = new ServerBootstrap()
                .channel(NioServerSocketChannel.class)
                .group(eventLoop, work)
                .childHandler(new ServerChannelHandler(handlers));

        this.stop();
    }

    public void stop() throws InterruptedException {
        final ChannelFuture channel = bootstrap.bind(new InetSocketAddress(8080)).sync();
        channel.channel().closeFuture().addListener(_channel -> {
            eventLoop.shutdownGracefully();
        });
    }
}
